const fs = require('fs');
const path = require('path');

const log4js = require('log4js');

const {resourcePath} = require('./filePath');
const clear = () => {
    let filepath = path.join(resourcePath, 'logs');
    if (!fs.existsSync(filepath)) return;
    let file = fs.readdirSync(filepath);
    let now = new Date().getTime();
    file.forEach(arr => {
        let filetime = arr.match(/\d{4}-\d{2}-\d{2}/)?.[0];
        if (!filetime) {
            return;
        }
        filetime = new Date(filetime).getTime();
        let left = now - filetime;
        if (left > 15 * 24 * 3600 * 1000)
            fs.unlinkSync(path.join(resourcePath, 'logs', arr));
    });
};

clear();
log4js.configure({
    replaceConsole: true,
    appenders: {
        stdout: {
            //控制台输出
            type: 'stdout',
        },
        err: {
            type: 'dateFile',
            filename: path.join(resourcePath, 'logs/logs'),
            pattern: 'err-yyyy-MM-dd.log',
            alwaysIncludePattern: true,
        },
        oth: {
            type: 'dateFile',
            filename: path.join(resourcePath, 'logs/logs'),
            pattern: 'oth-yyyy-MM-dd.log',
            alwaysIncludePattern: true,
        },
    },
    categories: {
        default: {appenders: ['stdout', 'oth'], level: 'debug'}, //appenders:采用的appender,取appenders项,level:设置级别
        err: {appenders: ['stdout', 'err'], level: 'error'},
    },
});

module.exports = log4js;
